package com.frontop.bigdata.modules.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frontop.bigdata.modules.model.BigDataOverview;
import com.frontop.bigdata.modules.mapper.BigDataOverviewMapper;
import com.frontop.bigdata.modules.service.BigDataOverviewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frontop.bigdata.util.BaiduDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 百度大数据--数据总览 服务实现类
 * </p>
 *
 * @author YangJia
 * @since 2022-02-14
 */
@Service
public class BigDataOverviewServiceImpl extends ServiceImpl<BigDataOverviewMapper, BigDataOverview> implements BigDataOverviewService {
    @Autowired
    BigDataOverviewMapper bigDataOverviewMapper;


    @Override
    @Transactional
    public void pullDataOverview(Long siteId, String date) {
        JSONObject body = new JSONObject();
        body.put("site_id",siteId);
        body.put("start_date",date);
        body.put("end_date",date);
        //浏览量，访客数，IP 数，平均停留时长（秒）
        body.put("metrics","pv_count,visitor_count,ip_count,avg_visit_time");
        body.put("method","overview/getTimeTrendRpt");

        JSONObject result = BaiduDataUtil.requestBaidu(body);
        if(result != null){
            //获取时间
            JSONArray times = result.getJSONObject("body")
                    .getJSONArray("data")
                    .getJSONObject(0)
                    .getJSONObject("result")
                    .getJSONArray("items").getJSONArray(0);
            //获取数据
            JSONArray values = result.getJSONObject("body")
                    .getJSONArray("data")
                    .getJSONObject(0)
                    .getJSONObject("result")
                    .getJSONArray("items").getJSONArray(1);

            if(times != null && times.size() > 0){
                List<BigDataOverview> bigDataOverviews = new ArrayList<>();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                for(int i=0; i < times.size();i++){
                    BigDataOverview bigDataOverview = new BigDataOverview();
                    bigDataOverview.setHour(times.getJSONArray(i).getInteger(0));
                    //如果浏览量是空的话 不记录这个数据
                    if(!(values.getJSONArray(i).get(0) instanceof Integer)){
                        continue;
                    }
                    bigDataOverview.setPvCount(values.getJSONArray(i).get(0) instanceof Integer?values.getJSONArray(i).getInteger(0):0);
                    bigDataOverview.setVisitorCount(values.getJSONArray(i).get(1) instanceof Integer?values.getJSONArray(i).getInteger(1):0);
                    bigDataOverview.setIpCount(values.getJSONArray(i).get(2) instanceof Integer?values.getJSONArray(i).getInteger(2):0);
                    bigDataOverview.setAvgVisitTime(values.getJSONArray(i).get(3) instanceof Integer?values.getJSONArray(i).getInteger(3):0);

                    bigDataOverview.setCreateDate(new Date());
                    bigDataOverview.setSiteId(siteId);
                    try {
                        bigDataOverview.setStatisticsDate(formatter.parse(date));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    bigDataOverviews.add(bigDataOverview);
                }
                Map<String,Object> map = new HashMap<>();
                try {
                    map.put("statistics_date",formatter.parse(date));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                map.put("site_id",siteId);
                //删除当天数据避免重复
                removeByMap(map);
                saveBatch(bigDataOverviews);
            }

        }
    }

    @Override
    public List<JSONObject> getSevenDaysOverview(Integer orgId,Integer day) {
        return bigDataOverviewMapper.getSevenDaysOverview(orgId,day);
    }

    @Override
    public JSONObject getOverviewTotalData(Integer orgId,Integer day) {
        return bigDataOverviewMapper.getOverviewTotalData(orgId,day);
    }

    @Override
    public JSONObject getOverviewAllTotal(Integer orgId) {
        return bigDataOverviewMapper.getOverviewAllTotal(orgId);
    }

}
